import axios, { AxiosRequestConfig } from 'axios';
import { environment } from 'environments/environment';
import { Respone } from './types';
import { message } from 'antd'
const instance = axios.create({
  headers: {
    'content-type': 'application/json',
    'Abp.TenantId': '1'
  }
});

function Authorization() {
  const INTERVAL_TIME = 10 * 60 * 1000;
  let timmer: any = 0;
  let access_token = localStorage.getItem('access_token') || null;
  let file_token = localStorage.getItem('file_token') || null;

  function cleare() {
    access_token = null;
    localStorage.removeItem('access_token');
    localStorage.removeItem('file_token');
  }

  function updateToken() {
    // @ts-ignore
    if (window.requestIdleCallback === undefined) {
      // @ts-ignore
      window.requestIdleCallback = (callback: () => {}) => {
        callback();
      }
    }
    // @ts-ignore
    window.requestIdleCallback(() => {
      axios.get(environment.prefix + '/Session/GetTokenInfo', { headers: { 'Authorization': 'Bearer ' + access_token } }).then(res => {
        try {
          if (res.data.success === true) {
            localStorage.setItem('file_token', res.data.result.access_token);
            file_token = res.data.result.access_token;
          }
        } catch (error) {
          console.warn(error)
        }
      }).catch((res) => {
        try {
          if (res.response.status === 401 && window.location.pathname !== '/login') {
            localStorage.removeItem('access_token');
            localStorage.removeItem('file_token');
            let to = `/login?to=` + btoa(window.location.pathname + window.location.search);
            message.warn('登陆已过期, 3秒后跳转至登陆页。');
            setTimeout(() => {
              window.location.href = to;
            }, 3000);
          }
        } catch (error) {
          message.warn('出现未知错误');
          console.error(res);
        }
      });
    });
  }
  // @ts-ignore
  window.requestIdleCallback(updateToken);
  if (access_token) {
    timmer = setInterval(updateToken, INTERVAL_TIME);
  }
  return {
    getAccessToken: () => {
      if (access_token === null) {
        return null;
      }
      return 'Bearer ' + access_token;
    },
    updateAccessToken: (token: string) => {
      localStorage.setItem('access_token', token);
      access_token = token;
      clearInterval(timmer);
      updateToken();
      timmer = setInterval(updateToken, INTERVAL_TIME);
    },
    getFileToken: () => {
      if (file_token === null) {
        return null;
      }
      return 'Bearer ' + file_token;
    },
    outLogin: () => {
      cleare();
    }
  }
}

export const Auth = Authorization();


instance.interceptors.request.use(conf => {
  conf.headers = Object.assign(conf.headers, {
    'Authorization': Auth.getAccessToken()
  });
  return conf;
});
instance.interceptors.response.use(response => {
  return response;
});

export const Request = instance;

function optimizeUrl(params: string) {
  if (params.indexOf('https://') !== -1) {
    return params;
  }
  if (params.indexOf('api') !== -1) {
    return environment.serveHost + params;
  }
  return environment.prefix + params;
}
function handleRespone(resp: any) {
  try {
    return Object.assign(resp.data, { statusCode: resp.status })
  } catch (error) {
    console.error(error);
    return null;
  }
}
function handleResponeError(resp: any) {
  try {
    return Object.assign(resp.response.data, { statusCode: resp.response.status })
  } catch (error) {
    console.log(error)
    return null;
  }
}

function optRequestParam(params: { page?: number, pageSize?: number, maxResultCount?: number, skipCount?: number; }): any {
  // console.log(JSON.parse(JSON.stringify(params)))
  if (params.maxResultCount !== undefined || params.skipCount !== undefined) {
    return params;
  }
  let result = params;
  if (params !== null && params !== undefined) {
    if (params.page !== null || params.page !== undefined) {
      let pageSize = params.pageSize ? params.pageSize : 10;
      // @ts-ignore
      let skipCount = ((params.page - 1) * pageSize) ? ((params.page - 1) * pageSize) : 0;
      // @ts-ignore
      result = Object.assign({}, params, { maxResultCount: pageSize, skipCount: skipCount })
    }
    delete result.page;
  }
  try {
    delete result.pageSize;
  } catch (error) {

  }
  // console.log(JSON.parse(JSON.stringify(result)))
  return result;
}

export function GET<T>(url: string, config?: AxiosRequestConfig) {

  if (config && config.params) {
    config.params = optRequestParam(config.params);
  }

  return Request.get(optimizeUrl(url), config).then(handleRespone, handleResponeError);
}

export function POST<T = any>(url: string, data: any, config?: AxiosRequestConfig): Promise<Respone<T>> {
  if (data) {
    data = optRequestParam(data);
  }
  let req = Request.post(optimizeUrl(url), data, config ? config : undefined);
  return req.then(handleRespone, handleResponeError);
}

export function UPDATE(url: string, config: AxiosRequestConfig) {
  return Request.post(optimizeUrl(url), config);
}

export function PUT<T = any>(url: string, data: any, config?: AxiosRequestConfig): Promise<Respone<T>> {
  if (data) {
    data = optRequestParam(data);
  }
  let req = Request.put(optimizeUrl(url), data, config ? config : undefined);
  return req.then(handleRespone, handleResponeError);
}

export function DELETE(url: string, config: AxiosRequestConfig) {
  return Request.delete(optimizeUrl(url), config).then(handleRespone, handleResponeError);
}

export function FormatePromise(pro: Promise<any>, errorMsg: string = '失败！') {
  return pro
    .then(res => {
      if (res.success === true) {
        return { error: null, data: res.result }
      } else {
        return { error: errorMsg, data: null };
      }
    }).catch(() => {
      return { error: '请求出错！', data: null }
    });
}
